package com.knife.news.logic.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.knife.news.logic.SurveyService;
import com.knife.news.object.Survey;

public class SurveyServiceImpl extends DAOSupportService implements SurveyService {
	private static SurveyServiceImpl surveyDAO = new SurveyServiceImpl();

	public static SurveyServiceImpl getInstance() {
		return surveyDAO;
	}

	public List<Survey> getAllSurvey(){
		return changeListType(this.dao.query(com.knife.news.model.Survey.class, "id!=''"));
	}
	
	public List<Survey> getSurveyBySid(String sid) {
		Collection<Object> paras = new ArrayList<Object>();
		paras.add(sid);
		return changeListType(this.dao.query(com.knife.news.model.Survey.class, "k_sid=?",paras));
	}

	public List<Survey> getSurveyBySql(String sql) {
		return changeListType(this.dao.query(com.knife.news.model.Survey.class, sql));
	}

	public List<Survey> getSurveyBySql(String sql, Collection<Object> paras, int begin, int end) {
		return changeListType(this.dao.query(com.knife.news.model.Survey.class, sql, paras, begin, end));
	}

	public Survey getSurveyById(String id) {
		com.knife.news.model.Survey asurvey=(com.knife.news.model.Survey)this.dao.get(com.knife.news.model.Survey.class, id);
		return new Survey(asurvey);
	}
	
	public List<Survey> getSurveyByUrl(String url){
		Collection<Object> paras = new ArrayList<Object>();
		paras.add(url);
		return changeListType(this.dao.query(com.knife.news.model.Survey.class, "k_url=?",paras));
	}
	
	public Survey getSurveyByUserAndPass(String user,String pass){
		Collection<Object> paras = new ArrayList<Object>();
		paras.add(user);
		List<Survey> surveys = changeListType(this.dao.query(com.knife.news.model.Survey.class, "k_user=?",paras));
		for(Survey s:surveys){
			if(s.getSid().length()>6){
				if(pass.equals(s.getSid().substring(s.getSid().length()-6))){
					return s;
				}
			}
		}
		return null;
	}

	public boolean saveSurvey(Survey survey) {
		com.knife.news.model.Survey bsurvey=new com.knife.news.model.Survey();
		survey.setId(bsurvey.getId());
		bsurvey.setSurvey(survey);
		return this.dao.save(bsurvey);
	}

	public boolean updateSurvey(Survey survey) {
		com.knife.news.model.Survey bsurvey=new com.knife.news.model.Survey();
		bsurvey.setSurvey(survey);
		return this.dao.update(bsurvey);
	}

	public boolean delSurvey(Survey survey) {
		com.knife.news.model.Survey bsurvey=new com.knife.news.model.Survey();
		bsurvey.setSurvey(survey);
		return this.dao.del(bsurvey);
	}
	
	public List<com.knife.news.object.Survey> changeListType(List<Object> news){
		List<Survey> results = new ArrayList<Survey>();
		if(news!=null){
			for (Object newobj : news) {
				com.knife.news.model.Survey bnews = (com.knife.news.model.Survey) newobj;
				Survey asurvey=new Survey(bnews);
				results.add(asurvey);
			}
		}
		return results;
	}
}